import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'

export default defineConfig(({ command, mode }) => {
  // 加载环境变量
  const env = loadEnv(mode, process.cwd(), '')
  
  return {
  base: '/his-refund/',
  plugins: [vue()],
  server: {
    port: 8089,
    host: true,
    open: true,
    cors: true,
    proxy: {
      '/api': {
        target: 'http://127.0.0.1:6724',
        changeOrigin: true,
        secure: false
      }
    }
  },
  build: {
    target: ['es2015', 'chrome58', 'firefox57', 'safari11'],
    outDir: 'dist',
    assetsDir: 'assets',
    sourcemap: false,
    chunkSizeWarningLimit: 1500, // 提高警告阈值到1500KB
    rollupOptions: {
      input: {
        main: resolve(__dirname, 'index.html')
      },
      output: {
        manualChunks(id) {
           // 将node_modules中的包分离到vendor chunk
           if (id.includes('node_modules')) {
             // Vue核心库
             if (id.includes('vue/') && !id.includes('vue-router')) {
               return 'vue-core';
             }
             // Vue生态系统
             if (id.includes('vue-router') || id.includes('pinia')) {
               return 'vue-ecosystem';
             }
             // Bootstrap相关
             if (id.includes('bootstrap')) {
               return 'ui-vendor';
             }
             // XLSX单独分包（较大的库）
             if (id.includes('xlsx')) {
               return 'xlsx-vendor';
             }
             // 加密库单独分包
             if (id.includes('crypto-js')) {
               return 'crypto-vendor';
             }
             // Axios等网络请求库
             if (id.includes('axios')) {
               return 'http-vendor';
             }
             // 其他工具库
             return 'vendor';
           }
           
           // 按页面组件分包
           if (id.includes('/src/views/')) {
             if (id.includes('RefundManagement')) {
               return 'refund-management';
             }
             if (id.includes('HisRefundVerify')) {
               return 'his-refund-verify';
             }
             return 'views';
           }
          },
         // 优化chunk文件名
        chunkFileNames: 'assets/js/[name]-[hash].js',
        entryFileNames: 'assets/js/[name]-[hash].js',
        assetFileNames: 'assets/[ext]/[name]-[hash].[ext]'
      }
    }
  },
  resolve: {
    alias: {
      '@': resolve(__dirname, 'src')
    }
  },
  css: {
    preprocessorOptions: {
      scss: {
        additionalData: `@import "@/styles/variables.scss";`
      }
    }
  },
  // 定义全局变量
  define: {
    __API_BASE_URL__: JSON.stringify(env.VITE_API_BASE_URL || 'http://localhost:6724'),
    __APP_ENV__: JSON.stringify(env.VITE_APP_ENV || 'development'),
    __APP_TITLE__: JSON.stringify(env.VITE_APP_TITLE || '退费审核管理系统')
  }
  }
})